/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.application.api;

import com.lap.auth.application.api.assembler.ApiAssembler;
import com.lap.auth.application.api.command.CreateApiCmd;
import com.lap.auth.application.api.dto.ApiTreeDto;
import com.lap.auth.domain.api.Api;
import com.lap.auth.domain.api.repository.ApiRepository;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * API接口应用服务层
 *
 * <ol>
 *   <li>不做业务规则，只做技术规则（加密/解密是技术实现，业务不关注）
 *   <li>取数，赋值，对象转换在这层执行
 *   <li>命名有规范，动词+领域名字
 *   <li>如查询比较多，建议分开领域QueryAppService,如:分页查询，分页查询返回关联字段
 * </ol>
 */
@RequiredArgsConstructor
@Service
public class ApiAppService {

  private final ApiAssembler apiAssembler;
  private final ApiRepository apiRepository;

  public List<ApiTreeDto> queryApiTree() {
    List<Api> allList = apiRepository.findList();
    List<ApiTreeDto> list = apiAssembler.toDtoList(allList);
    return apiAssembler.convertTree(list);
  }

  @Transactional(rollbackFor = Exception.class)
  public void createApis(String module, List<CreateApiCmd> cmdList) {
    List<Api> list = apiAssembler.toDomains(cmdList);
    apiRepository.deleteByModule(module);
    apiRepository.saveAll(list);
  }
}
